package com.ljh.mall.controller;

import com.ljh.mall.mybatis.model.UmsAdmin;
import com.ljh.mall.mybatis.result.Result;
import com.ljh.mall.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/index")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }

    @PostMapping("/adminLogin")
    @ResponseBody
    public String login(Model model, String username, String password) {
        ModelAndView mav = new ModelAndView();

        UmsAdmin admin = new UmsAdmin();
        admin.setUsername(username);
        admin.setPassword(password);

        UmsAdmin dbAdmin = this.adminService.login(admin);
        if(ObjectUtils.isEmpty(dbAdmin)) {
            mav.setStatus(HttpStatus.OK);
            mav.addObject("msg", "该用户不存在");
            return mav.toString();
        }else {
            mav.addObject("admin", dbAdmin);
        }

        return mav.toString();
    }

    @RequestMapping("/loginByMd5")
    @ResponseBody
    public Result<UmsAdmin> loginByMd5(String username,String password){
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setUsername(username);
        umsAdmin.setPassword(password);
        Result<UmsAdmin> login = adminService.loginByMD5(umsAdmin);
        return login;
    }

    @RequestMapping("/adminReg")
    @ResponseBody
    public String adminRegister(UmsAdmin umsAdmin){
        ModelAndView mav = new ModelAndView();
        if (umsAdmin.getUsername() != null && umsAdmin.getPassword() != null){
            adminService.register(umsAdmin);
            mav.addObject("admin",umsAdmin);
            return mav.toString();
        }else {
            mav.setStatus(HttpStatus.OK);
            mav.addObject("msg","用户名和密码不能为空！");
            return mav.toString();
        }
    }


}
